package com.ledou44.ledourpc.servicehandler;

import com.alibaba.fastjson.JSON;
import com.ledou44.ledourpc.ServiceBeanFactory;
import com.ledou44.ledourpc.dto.LedouMethod;
import com.ledou44.ledourpc.dto.LedouRpcDTO;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.lang.reflect.Method;

/**
 * @author ledou44
 * 默认handler
 */
public class DefaultServiceHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        LedouRpcDTO ledouRpcDTO = JSON.parseObject(String.valueOf(msg), LedouRpcDTO.class);
        Class<?> serviceClass = ledouRpcDTO.getBaseClass();
        LedouMethod rpcMethod = ledouRpcDTO.getMethod();
        Object service = ServiceBeanFactory.beanFactory.get(serviceClass.getName());
        Method[] allMethods = serviceClass.getDeclaredMethods();
        Object invokeResult = null;
        for(Method method : allMethods) {
            if(method.getName().equals(rpcMethod.getName())) {
                invokeResult = method.invoke(service, ledouRpcDTO.getObjects());
            }
        }
        ctx.writeAndFlush(JSON.toJSONString(invokeResult));
        //将消息传递给下一个handler
        ctx.fireChannelRead(msg);
    }
}
